package vk;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 * User: ekozobrodov
 */
public class AuthComponent {
    public static final String APP_ID = "3255677";
    private static final String REDIRECT_URL = "http://oauth.vk.com/blank.html";
    private static final String LOGIN_URL = "https://oauth.vk.com/authorize?" +
            "client_id=" + APP_ID + "&" +
            "scope=video&" +
            "redirect_uri=" + REDIRECT_URL + "&" +
            "display=page&" +
            "response_type=token";

    private static String accessToken;
    private static int uid;

    public static String getAccessToken() {
        return accessToken;
    }

    public static int getUid() {
        return uid;
    }

    private AuthCompleteListener listener;

    public AuthComponent(AuthCompleteListener listener) {
        this.listener = listener;
    }

    public void start(Stage stage) throws Exception {
        Group root = new Group();
        stage.setScene(new Scene(root));
        stage.setTitle("VK Login");
        stage.setWidth(800);
        stage.setHeight(400);
        stage.setResizable(false);
        WebView webView = new WebView();

        final WebEngine webEngine = webView.getEngine();
        webEngine.locationProperty().addListener(new ChangeListener<String>() {
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (newValue.contains("access_token")) {
                    String[] paramsArray = (newValue.split("#")[1]).split("&");
                    for (String param : paramsArray) {
                        String[] parts = param.split("=");
                        if (parts[0].equals("access_token")) {
                            accessToken = parts[1];
                        } else if (parts[0].equals("user_id")) {
                            uid = Integer.parseInt(parts[1]);
                        } else if (parts[0].equals("error")) {
                            System.err.println(parts[1]);
                            System.exit(1);
                        }
                        if (accessToken != null && uid > 0) {
                            listener.handle();
                        }
                    }
                }
            }
        });
        webEngine.load(LOGIN_URL);

        VBox vBox = new VBox(5);
        vBox.getChildren().setAll(webView);
        VBox.setVgrow(webView, Priority.ALWAYS);

        root.getChildren().add(vBox);
        stage.show();
    }
}
